package com.brainhealth.customer.service.impl;

import java.util.Date;
import java.util.List;

import com.brainhealth.common.constant.NumberConstants;
import com.brainhealth.common.enums.*;
import com.brainhealth.common.utils.DateUtils;
import com.brainhealth.common.utils.SnowFlakeUtil;
import com.brainhealth.customer.domain.*;
import com.brainhealth.customer.mapper.ScoreMallGoodsMapper;
import com.brainhealth.customer.mapper.ScoreMallOrderDetailMapper;
import com.brainhealth.customer.service.*;
import com.brainhealth.utils.CommonUtils;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import com.brainhealth.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import com.brainhealth.customer.mapper.ScoreMallOrderMapper;

import javax.servlet.http.HttpServletRequest;

/**
 * 积分商城订单Service业务层处理
 * 
 * @author wolong
 * @date 2023-11-01
 */
@Service
public class ScoreMallOrderServiceImpl implements IScoreMallOrderService 
{
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private ScoreMallOrderMapper scoreMallOrderMapper;
    @Autowired
    private ScoreMallOrderDetailMapper scoreMallOrderDetailMapper;
    @Autowired
    private IScoreConsumeRecordService scoreConsumeRecordService;
    @Autowired
    private ICustomerService customerService;
    @Autowired
    private IRoomUserPropertyService roomUserPropertyService;
    @Autowired
    private IScoreMallGoodsService scoreMallGoodsService;
    @Autowired
    private IRoomChatTokensService roomChatTokensService;

    /**
     * 查询积分商城订单
     * 
     * @param id 积分商城订单主键
     * @return 积分商城订单
     */
    @Override
    public ScoreMallOrder selectScoreMallOrderById(Long id)
    {
        return scoreMallOrderMapper.selectScoreMallOrderById(id);
    }

    @Override
    public ScoreMallOrder selectScoreMallOrderByOrderId(String orderId) {
        return scoreMallOrderMapper.selectScoreMallOrderByOrderId(orderId);
    }

    @Override
    public List<ScoreMallOrder> getScoreMallOrderList(ScoreMallOrder scoreMallOrder) {
        return scoreMallOrderMapper.getScoreMallOrderList(scoreMallOrder);
    }

    /**
     * 查询积分商城订单列表
     * 
     * @param scoreMallOrder 积分商城订单
     * @return 积分商城订单
     */
    @Override
    public List<ScoreMallOrder> selectScoreMallOrderList(ScoreMallOrder scoreMallOrder)
    {
        return scoreMallOrderMapper.selectScoreMallOrderList(scoreMallOrder);
    }

    /**
     * 新增积分商城订单
     * 
     * @param scoreMallOrder 积分商城订单
     * @return 结果
     */
    @Transactional
    @Override
    public int insertScoreMallOrder(ScoreMallOrder scoreMallOrder)
    {
        scoreMallOrder.setCreateTime(DateUtils.getNowDate());
        int rows = scoreMallOrderMapper.insertScoreMallOrder(scoreMallOrder);
        insertScoreMallOrderDetail(scoreMallOrder);
        return rows;
    }

    /**
     * 修改积分商城订单
     * 
     * @param scoreMallOrder 积分商城订单
     * @return 结果
     */
    @Transactional
    @Override
    public int updateScoreMallOrder(ScoreMallOrder scoreMallOrder)
    {
        scoreMallOrder.setUpdateTime(DateUtils.getNowDate());
        scoreMallOrderMapper.deleteScoreMallOrderDetailByScoreMallOrderId(scoreMallOrder.getId());
        insertScoreMallOrderDetail(scoreMallOrder);
        return scoreMallOrderMapper.updateScoreMallOrder(scoreMallOrder);
    }

    /**
     * 批量删除积分商城订单
     * 
     * @param ids 需要删除的积分商城订单主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteScoreMallOrderByIds(Long[] ids)
    {
        scoreMallOrderMapper.deleteScoreMallOrderDetailByScoreMallOrderIds(ids);
        return scoreMallOrderMapper.deleteScoreMallOrderByIds(ids);
    }

    /**
     * 删除积分商城订单信息
     * 
     * @param id 积分商城订单主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteScoreMallOrderById(Long id)
    {
        scoreMallOrderMapper.deleteScoreMallOrderDetailByScoreMallOrderId(id);
        return scoreMallOrderMapper.deleteScoreMallOrderById(id);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean useScoreBuyGoods(HttpServletRequest request, Long goodsId)
    {
        long ts = DateUtils.getTimeMillis();
        Customer customer = CommonUtils.getCustomerByRequest(request);
        ScoreMallGoods scoreMallGoods = new ScoreMallGoods();
        scoreMallGoods.setGoodsId(goodsId);
        List<ScoreMallGoods> scoreMallGoodsList = scoreMallGoodsService.selectScoreMallGoodsList(scoreMallGoods);

        if (CollectionUtils.isNotEmpty(scoreMallGoodsList))
        {
            ScoreMallGoods goods = scoreMallGoodsList.get(0);
            if (goods.getGoodsScore() > customer.getScore()) {
                logger.info("ts：{}, 用户{}有积分{}, 商品{}所需积分{}", ts, customer.getCustomerId(), customer.getScore(), goods.getGoodsId(), goods.getGoodsScore());
                return false;
            }
            RoomUserProperty roomUserProperty = new RoomUserProperty();
            roomUserProperty.setCustomerId(customer.getCustomerId());
            roomUserProperty.setGoodsId(goods.getGoodsId());
            roomUserProperty.setYn(YNEnum.NO.getCode());
            List<RoomUserProperty> roomUserPropertyList = roomUserPropertyService.selectRoomUserPropertyList(roomUserProperty);
            if (CollectionUtils.isNotEmpty(roomUserPropertyList)) {
                logger.info("ts:：{}, 用户{}已经拥有商品{}", ts, customer.getCustomerId(), goodsId);
                boolean result = roomUserPropertyList.stream().allMatch(item -> null != item.getGoodsType() && GoodsType.AIPackage.getCode() == item.getGoodsType());
                if (!result) {
                    return false;
                }
            }
            ScoreMallOrder scoreMallOrder = new ScoreMallOrder();
            scoreMallOrder.setCustomerId(customer.getCustomerId());
            scoreMallOrder.setPayTime(new Date());
            scoreMallOrder.setPayType(PayType.ScorePay);
            scoreMallOrder.setScoreMallOrderId(SnowFlakeUtil.getDefaultSnowFlakeId().toString());
            scoreMallOrder.setStatus(PayStatus.Paid);
            scoreMallOrder.setTotalPayAmount(0l);
            scoreMallOrder.setTotalScoreAmount(goods.getGoodsScore());
            scoreMallOrder.setCreateTime(new Date());
            scoreMallOrder.setYn(0);
            ScoreMallOrderDetail scoreMallOrderDetail = new ScoreMallOrderDetail();
            scoreMallOrderDetail.setGoodsAmount(0l);
            scoreMallOrderDetail.setGoodsId(goods.getGoodsId());
            scoreMallOrderDetail.setGoodsMoney(0l);
            scoreMallOrderDetail.setGoodsPayRule(goods.getPayRule());
            scoreMallOrderDetail.setGoodsScore(goods.getGoodsScore());
            scoreMallOrderDetail.setScoreMallOrderId(scoreMallOrder.getScoreMallOrderId());
            scoreMallOrderDetail.setScoreMallOrderDetailId(SnowFlakeUtil.getDefaultSnowFlakeId().toString());
            scoreMallOrderDetail.setYn(0);
            int result = scoreMallOrderMapper.insertScoreMallOrder(scoreMallOrder);
            if (result > 0)
            {
                scoreMallOrderDetailMapper.insertScoreMallOrderDetail(scoreMallOrderDetail);
                addScoreConsumeRecord(ts, scoreMallOrder, goods);
                decrUserScore(ts, scoreMallOrder);
                addRoomUserProperty(ts, scoreMallOrder, goods);
                return true;
            }
        }
        logger.info("ts：{}, 商品ID{}不存在", ts, goodsId);
        return false;
    }

    // 增加积分消耗记录
    private Integer addScoreConsumeRecord(Long ts,ScoreMallOrder scoreMallOrder,ScoreMallGoods goods){
        Long customerId = scoreMallOrder.getCustomerId();
        String strCustomerId = null==customerId?"":String.valueOf(customerId);
        Date now = DateUtils.getNowDate();
        ScoreConsumeRecord scoreConsumeRecord = new ScoreConsumeRecord();
        Integer recordId = scoreConsumeRecordService.getMaxScoreConsumeRecordId();
        recordId = null == recordId ? NumberConstants.ONE : recordId + 1;
        scoreConsumeRecord.setScoreConsumeRecordId(Long.valueOf(recordId));
        scoreConsumeRecord.setCustomerId(customerId);
        scoreConsumeRecord.setScoreMallOrderId(scoreMallOrder.getScoreMallOrderId());
        // Long goodsId = scoreMallOrderDetail.getGoodsId();
        // ScoreMallGoods scoreMallGoods = new ScoreMallGoods();
        // scoreMallGoods.setGoodsId(goodsId);
        // List<ScoreMallGoods> scoreMallGoodsList = scoreMallGoodsService.selectScoreMallGoodsList(scoreMallGoods);
        // if (CollectionUtils.isNotEmpty(scoreMallGoodsList)) {
        //     ScoreMallGoods goods = scoreMallGoodsList.get(0);
        //
        // }
        scoreConsumeRecord.setGoodsName(goods.getGoodsName());
        scoreConsumeRecord.setGoodsImg(goods.getGoodsImg());
        scoreConsumeRecord.setScoreDesc("兑换"+goods.getGoodsName()+"消耗");
        scoreConsumeRecord.setScore(goods.getGoodsScore());
        scoreConsumeRecord.setYn(YNEnum.NO.getCode());
        scoreConsumeRecord.setCreateUser(strCustomerId);
        scoreConsumeRecord.setCreateTime(now);
        scoreConsumeRecord.setUpdateUser(strCustomerId);
        scoreConsumeRecord.setUpdateTime(now);

        int insertResult = scoreConsumeRecordService.insertScoreConsumeRecord(scoreConsumeRecord);
        logger.info("ts：{}增加积分消耗记录结果{}", ts, insertResult);
        return insertResult;
    }

    // 用户表减去积分
    private Integer decrUserScore(Long ts, ScoreMallOrder scoreMallOrder) {
        Long customerId = scoreMallOrder.getCustomerId();
        Long totalScoreAmount = scoreMallOrder.getTotalScoreAmount();
        totalScoreAmount = null == totalScoreAmount ? NumberConstants.ZERO : totalScoreAmount;
        Customer customer = customerService.selectCustomerByCustomerId(customerId);
        Long score = customer.getScore();
        score = null == score ? NumberConstants.ZERO : score;
        score = score - totalScoreAmount;
        customer.setScore(score);
        int updateResult = customerService.updateCustomer(customer);
        logger.info("ts：{}用户{}减去积分{}结果{}", ts, customerId, totalScoreAmount, updateResult);
        customerService.refreshToken(ts,customer);
        return updateResult;
    }

    // 道具表增加道具
    private Integer addRoomUserProperty(Long ts, ScoreMallOrder scoreMallOrder, ScoreMallGoods goods) {
        Long customerId = scoreMallOrder.getCustomerId();
        String strCustomerId = null == customerId ? "" : String.valueOf(customerId);
        Date now = DateUtils.getNowDate();
        RoomUserProperty roomUserProperty = new RoomUserProperty();
        Integer propertyId = roomUserPropertyService.getMaxPropertyId();
        propertyId = null == propertyId ? NumberConstants.ONE : propertyId + 1;
        roomUserProperty.setPropertyId(Long.valueOf(propertyId));
        roomUserProperty.setCustomerId(customerId);
        BeanUtils.copyProperties(goods,roomUserProperty);

        // Long goodsId = scoreMallOrderDetail.getGoodsId();
        // roomUserProperty.setGoodsId(goodsId);
        // ScoreMallGoods scoreMallGoods = new ScoreMallGoods();
        // scoreMallGoods.setGoodsId(goodsId);
        // List<ScoreMallGoods> scoreMallGoodsList = scoreMallGoodsService.selectScoreMallGoodsList(scoreMallGoods);
        // if (CollectionUtils.isNotEmpty(scoreMallGoodsList)) {
        //     ScoreMallGoods goods = scoreMallGoodsList.get(0);
        //
        // }
        // roomUserProperty.setGoodsId(goods.getGoodsId());
        // roomUserProperty.setGoodsCategoryId(goods.getCategoryId().intValue());
        // roomUserProperty.setGoodsType(goods.getGoodsType().getCode());
        // roomUserProperty.setGoodsShortName(goods.getGoodsShortName());
        // roomUserProperty.setGoodsName(goods.getGoodsName());
        // roomUserProperty.setGoodsImg(goods.getGoodsImg());
        // roomUserProperty.setGoodsImg(goods.getGoodsImg());
        // roomUserProperty.setGoodsInstructions(goods.getGoodsInstructions());
        // roomUserProperty.setGoodsScore(goods.getGoodsScore());

        //从商品信息表取值
        roomUserProperty.setGoodsCategoryId(goods.getCategoryId().intValue());
        roomUserProperty.setGoodsType(goods.getGoodsType().getCode());
        roomUserProperty.setGoodsStatus(PropertyStatusEnum.NOT_USED.getCode());
        roomUserProperty.setYn(YNEnum.NO.getCode());
        roomUserProperty.setCreateUser(strCustomerId);
        roomUserProperty.setCreateTime(now);
        roomUserProperty.setUpdateUser(strCustomerId);
        roomUserProperty.setUpdateTime(now);

        int insertResult = roomUserPropertyService.insertRoomUserProperty(roomUserProperty);
        if (GoodsType.AIPackage.getCode() == roomUserProperty.getGoodsType()) {
            RoomChatTokens roomChatTokens = new RoomChatTokens();
            roomChatTokens.setCustomerId(customerId);
            List<RoomChatTokens> roomChatTokensList = roomChatTokensService.selectRoomChatTokensList(roomChatTokens);
            if (CollectionUtils.isNotEmpty(roomChatTokensList)) {
                RoomChatTokens chatTokens = roomChatTokensList.get(0);
                Long chatPacketSum = chatTokens.getChatPacketSum();
                chatPacketSum = null == chatPacketSum ? Long.valueOf(NumberConstants.ONE) : chatPacketSum + 1;
                chatTokens.setChatPacketSum(chatPacketSum);
                chatTokens.setUpdateTime(now);
                int updateRoomChatTokensResult = roomChatTokensService.updateRoomChatTokens(chatTokens);
                logger.info("ts:{}, 更新聊天字数结果{}", ts, updateRoomChatTokensResult);
            } else {
                roomChatTokens.setChatPacketSum(Long.valueOf(NumberConstants.ONE));
                roomChatTokens.setChatPacketUsed(Long.valueOf(NumberConstants.ZERO));
                roomChatTokens.setCompletedChatTokens(Long.valueOf(NumberConstants.ZERO));
                roomChatTokens.setYn(YNEnum.NO.getCode());
                roomChatTokens.setCreateUser(strCustomerId);
                roomChatTokens.setCreateTime(now);
                roomChatTokens.setUpdateUser(strCustomerId);
                roomChatTokens.setUpdateTime(now);
                int insertRoomChatTokensResult = roomChatTokensService.insertRoomChatTokens(roomChatTokens);
                logger.info("ts:{}, 新增聊天字数结果{}", ts, insertRoomChatTokensResult);
            }
        }
        logger.info("ts：{}增加道具记录结果{}", ts, insertResult);
        return insertResult;
    }

    /**
     * 新增积分商城订单明细表信息
     * 
     * @param scoreMallOrder 积分商城订单对象
     */
    public void insertScoreMallOrderDetail(ScoreMallOrder scoreMallOrder)
    {
        List<ScoreMallOrderDetail> scoreMallOrderDetailList = scoreMallOrder.getScoreMallOrderDetailList();
        String orderId = scoreMallOrder.getScoreMallOrderId();
        if (StringUtils.isNotNull(scoreMallOrderDetailList))
        {
            List<ScoreMallOrderDetail> list = new ArrayList<ScoreMallOrderDetail>();
            for (ScoreMallOrderDetail scoreMallOrderDetail : scoreMallOrderDetailList)
            {
                scoreMallOrderDetail.setScoreMallOrderId(orderId);
                scoreMallOrderDetail.setCreateTime(new Date());
                list.add(scoreMallOrderDetail);
            }
            if (list.size() > 0)
            {
                scoreMallOrderMapper.batchScoreMallOrderDetail(list);
            }
        }
    }
}
